import { ref, computed, onMounted } from 'vue'
import type { Message, Conversation, ProcessingTask, ResultPanel } from '../../types/home'
import { 
  getConversations, 
  getConversationDetail, 
  createConversation, 
  deleteConversation 
} from '../../api/conversation'
import { getProcessingTaskConfig } from '../../api/processing'

export function useHomeState() {
  // 基础状态
  const sidebarOpen = ref(true)
  const selectedRobot = ref('robot1')
  const searchQuery = ref('')
  const selectedConversation = ref<Conversation | null>(null)
  const newMessage = ref('')
  const isLoading = ref(false)
  const currentConversationType = ref<'knowledge' | 'data' | 'image' | 'code'>('knowledge')
  
  // 数据状态
  const messages = ref<Message[]>([])
  const conversations = ref<Conversation[]>([])
  const progress = ref(0)
  const processingTasks = ref<ProcessingTask[]>([])
  const resultPanels = ref<ResultPanel[]>([])

  // 计算属性
  const filteredConversations = computed(() => {
    if (!searchQuery.value) return conversations.value
    return conversations.value.filter(conv => 
      conv.title.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  })
  
  // 对话统计
  const conversationStats = computed(() => {
    const stats = {
      total: conversations.value.length,
      knowledge: 0,
      data: 0,
      image: 0,
      code: 0
    }
    
    conversations.value.forEach(conv => {
      if (stats.hasOwnProperty(conv.type)) {
        stats[conv.type as keyof typeof stats]++
      }
    })
    
    return stats
  })

  // 重置状态
  const resetState = () => {
    messages.value = []
    processingTasks.value = []
    resultPanels.value = []
    progress.value = 0
    selectedConversation.value = null
    currentConversationType.value = 'knowledge'
  }

  // 创建新对话
  const createNewConversation = async () => {
    try {
      selectedConversation.value = null
      resetState()
    } catch (error) {
      console.error('Failed to create new conversation:', error)
      throw error
    }
  }

  // 初始化对话列表
  const initializeConversations = async () => {
    try {
      isLoading.value = true
      const conversationList = await getConversations()
      conversations.value = conversationList
      
      // 如果有对话，自动加载第一个
      if (conversationList.length > 0 && !selectedConversation.value) {
        await loadConversation(conversationList[0])
      }
    } catch (error) {
      console.error('Failed to initialize conversations:', error)
      // 如果API失败，使用默认对话
      conversations.value = [
        { 
          id: 1, 
          title: '深圳监测站分析方法', 
          created_at: new Date(Date.now() - 86400000), 
          type: 'knowledge' 
        },
        { 
          id: 2, 
          title: '深圳AQI趋势分析', 
          created_at: new Date(Date.now() - 172800000), 
          type: 'data' 
        },
        { 
          id: 3, 
          title: '臭氧变化趋势图分析', 
          created_at: new Date(Date.now() - 259200000), 
          type: 'image' 
        },
        { 
          id: 4, 
          title: 'Python代码性能分析', 
          created_at: new Date(Date.now() - 345600000), 
          type: 'code' 
        }
      ]
    } finally {
      isLoading.value = false
    }
  }

  // 加载对话数据
  const loadConversation = async (conversation: Conversation) => {
    try {
      isLoading.value = true
      selectedConversation.value = conversation
      currentConversationType.value = conversation.type
      
      // 清空当前消息
      messages.value = []
      processingTasks.value = []
      resultPanels.value = []
      progress.value = 0
      
      // 从API获取对话详情
      const conversationDetail = await getConversationDetail(conversation.id)
      
      // 设置消息
      messages.value = conversationDetail.messages.map(msg => ({
        ...msg,
        created_at: new Date(msg.created_at)
      }))
      
      // 初始化处理任务
      await initializeProcessingTasks(conversation.type)
      
      console.log('选中对话:', conversation.title, '加载消息数:', messages.value.length)
    } catch (error) {
      console.error('Failed to load conversation:', error)
      // 如果API失败，使用模拟数据
      loadMockConversationData(conversation)
    } finally {
      isLoading.value = false
    }
  }

  // 加载模拟对话数据（当API失败时的备用方案）
  const loadMockConversationData = (conversation: Conversation) => {
    console.log('Loading mock data for conversation:', conversation.title)
    
    if (conversation.id === 1) {
      // Vue3对话
      messages.value = [
        {
          id: 1,
          role: 'user',
          content: '你好，请介绍一下Vue3的主要特性',
          created_at: new Date('2024-01-15T10:30:00')
        },
        {
          id: 2,
          role: 'assistant',
          content: 'Vue3是一个现代化的前端框架，主要特性包括：\n\n1. **Composition API** - 提供更灵活的组件逻辑组织方式\n2. **更好的TypeScript支持** - 内置TS支持，提供更好的类型安全\n3. **性能优化** - 重构虚拟DOM，提升渲染性能\n4. **更小的包体积** - 通过Tree-shaking减少最终包大小\n5. **新的组件生命周期** - 更清晰的组件生命周期钩子\n\n您想了解哪个特性的更多细节吗？',
          created_at: new Date('2024-01-15T10:30:15')
        }
      ]
    } else if (conversation.id === 2) {
      // 数据分析对话
      messages.value = [
        {
          id: 1,
          role: 'user',
          content: '最近一个月深圳市的AQI变化趋势，请帮我分析一下',
          created_at: new Date('2024-01-14T14:20:00')
        },
        {
          id: 2,
          role: 'assistant',
          content: '根据最近一个月深圳市的AQI数据分析，我为您总结以下趋势：\n\n**总体趋势：**\n- AQI整体呈现下降趋势，空气质量逐步改善\n- 优良天数占比达到85%，较上月提升5个百分点\n- 轻度污染天数减少3天，中度污染天数减少1天\n\n**主要污染物：**\n- PM2.5仍然是主要污染物，占比45%\n- PM10占比25%，O3占比20%，其他污染物占比10%\n\n**建议措施：**\n1. 继续加强工业排放管控\n2. 优化交通流量管理\n3. 增加城市绿化覆盖率',
          created_at: new Date('2024-01-14T14:20:30')
        }
      ]
    } else if (conversation.id === 3) {
      // 图像识别对话
      messages.value = [
        {
          id: 1,
          role: 'user',
          content: '帮我从空气质量管控的角度，对这张图片做解读',
          created_at: new Date('2024-01-13T09:15:00')
        },
        {
          id: 2,
          role: 'assistant',
          content: '从空气质量管控的角度分析这张图片：\n\n**图像识别结果：**\n- 识别到城市天际线，可见度良好\n- 天空呈现淡蓝色，无明显污染层\n- 建筑物轮廓清晰，无雾霾现象\n\n**空气质量评估：**\n- 当前AQI水平估计在50-80之间\n- 空气质量等级：良\n- 主要污染物浓度较低\n\n**管控建议：**\n1. 继续维持现有管控措施\n2. 加强重点区域监测\n3. 做好预警预案准备',
          created_at: new Date('2024-01-13T09:15:45')
        }
      ]
    } else if (conversation.id === 4) {
      // 代码优化对话
      messages.value = [
        {
          id: 1,
          role: 'user',
          content: '请帮我审查这段Python代码，找出潜在的性能问题',
          created_at: new Date('2024-01-12T16:45:00')
        },
        {
          id: 2,
          role: 'assistant',
          content: '经过代码审查，发现以下性能问题和优化建议：\n\n**发现的问题：**\n1. **重复计算问题** - 在循环中重复计算相同的值\n2. **内存使用不当** - 大量临时对象创建\n3. **算法复杂度** - O(n²)复杂度可以优化\n\n**优化建议：**\n1. 使用缓存机制避免重复计算\n2. 采用生成器减少内存占用\n3. 优化算法结构，降低时间复杂度\n\n**预期改进：**\n- 执行时间减少60-70%\n- 内存使用降低40-50%\n- 代码可读性提升',
          created_at: new Date('2024-01-12T16:46:00')
        }
      ]
    }
    
    // 初始化处理任务
    initializeProcessingTasks(conversation.type)
  }

  // 初始化处理任务
  const initializeProcessingTasks = async (type: string) => {
    try {
      const taskConfigs = await getProcessingTaskConfig(type)
      processingTasks.value = taskConfigs
    } catch (error) {
      console.error('Failed to initialize processing tasks:', error)
      processingTasks.value = []
    }
    resultPanels.value = []
    progress.value = 0
  }

  // 选择对话
  const selectConversation = async (conversation: Conversation) => {
    try {
      await loadConversation(conversation)
    } catch (error) {
      console.error('Failed to select conversation:', error)
      throw error
    }
  }

  // 删除对话
  const removeConversation = async (conversationId: number) => {
    try {
      await deleteConversation(conversationId)
      conversations.value = conversations.value.filter(conv => conv.id !== conversationId)
      
      // 如果删除的是当前选中的对话，清空状态
      if (selectedConversation.value?.id === conversationId) {
        resetState()
      }
    } catch (error) {
      console.error('Failed to delete conversation:', error)
      throw error
    }
  }

  // 发送消息
  const sendMessage = async (content: string) => {
    try {
      if (!selectedConversation.value) {
        // 如果没有选中的对话，创建一个新对话
        const newConversation = await createConversation({
          title: content.substring(0, 50) + (content.length > 50 ? '...' : ''),
          type: 'knowledge',
          initial_message: content
        })
        
        conversations.value.unshift(newConversation)
        await loadConversation(newConversation)
      } else {
        // 添加用户消息
        const userMessage: Message = {
          id: Date.now(),
          role: 'user',
          content,
          created_at: new Date()
        }
        messages.value.push(userMessage)
        
        // 模拟AI回复
        setTimeout(() => {
          const assistantMessage: Message = {
            id: Date.now() + 1,
            role: 'assistant',
            content: '收到您的消息，我正在处理中...',
            created_at: new Date()
          }
          messages.value.push(assistantMessage)
        }, 1000)
      }
    } catch (error) {
      console.error('Failed to send message:', error)
      throw error
    }
  }

  // 组件挂载时初始化
  onMounted(() => {
    initializeConversations()
  })

  return {
    // 基础状态
    sidebarOpen,
    selectedRobot,
    searchQuery,
    selectedConversation,
    newMessage,
    isLoading,
    currentConversationType,
    
    // 数据状态
    messages,
    conversations,
    progress,
    processingTasks,
    resultPanels,
    
    // 计算属性
    filteredConversations,
    conversationStats,
    
    // 方法
    resetState,
    createNewConversation,
    loadConversation,
    selectConversation,
    removeConversation,
    sendMessage,
    initializeProcessingTasks,
    
    // UI交互方法
    toggleSidebar: () => {
      sidebarOpen.value = !sidebarOpen.value
    },
    updateSelectedRobot: (value: string) => {
      selectedRobot.value = value
    },
    updateSearchQuery: (value: string) => {
      searchQuery.value = value
    },
    handlePanelClick: (panel: any) => {
      console.log('Panel clicked:', panel)
    }
  }
}